﻿using BusinessLayer;
using BusinessLayer.VDataEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using TrialManagementTool.Auth;
using TrialManagmentTool.Helper;
using TrialManagmentTool.Models;

namespace TrialManagementTool.Helper
{
    public class WechatAuthenticationAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string userid = string.Empty;
#if (DEBUG)
            {
                userid = "zhangyanxiang";
            }
#else
            userid = Authenticate.CheckWeixinUserID();
#endif
            if (string.IsNullOrEmpty(userid))
            {
                HttpContext.Current.Response.Redirect("~/Error/AuthFail");
            }
            else
            {
                VPromoter promoter = System.Web.HttpContext.Current.Session["PromoterInfo"] as VPromoter;
                if (promoter == null)
                {
                    string uid=UserHelper.GetUserInfoFromCookie();
                    if (!string.IsNullOrEmpty(uid))
                    {
                        promoter = JsonHelper.ParseFromJson<VPromoter>(uid);
                    }

                    if (promoter == null)
                    {
                        promoter = PromoterBusiness.ValidatePromoter(userid);
                        if (promoter == null)
                        {
                            HttpContext.Current.Response.Redirect("~/Error/AuthFail");
                        }
                        else
                        {
                            HttpContext.Current.Session["PromoterInfo"] = promoter;
                        }
                    }
                }
            }

        }

    }
}